<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/model/counter_sample.html">
<link rel="import" href="/tracing/model/event_container.html">

<script>
'use strict';

tr.exportTo('tr.model', function() {
  const CounterSample = tr.model.CounterSample;

  /**
   * A container holding all samples of a given measurement over time.
   *
   * As an example, a counter series might measure the throughput of data sent
   * over a USB connection, with each sample representing the instantaneous
   * throughput of the connection.
   *
   * @constructor
   * @extends {EventContainer}
   */
  function CounterSeries(name, color) {
    tr.model.EventContainer.call(this);

    this.name_ = name;
    this.color_ = color;

    this.timestamps_ = [];
    this.samples_ = [];

    // Set by counter.addSeries
    this.counter = undefined;
    this.seriesIndex = undefined;
  }

  CounterSeries.prototype = {
    __proto__: tr.model.EventContainer.prototype,

    get length() {
      return this.timestamps_.length;
    },

    get name() {
      return this.name_;
    },

    get color() {
      return this.color_;
    },

    get samples() {
      return this.samples_;
    },

    get timestamps() {
      return this.timestamps_;
    },

    getSample(idx) {
      return this.samples_[idx];
    },

    getTimestamp(idx) {
      return this.timestamps_[idx];
    },

    addCounterSample(ts, val) {
      const sample = new CounterSample(this, ts, val);
      this.addSample(sample);
      return sample;
    },

    addSample(sample) {
      this.timestamps_.push(sample.timestamp);
      this.samples_.push(sample);
    },

    getStatistics(sampleIndices) {
      let sum = 0;
      let min = Number.MAX_VALUE;
      let max = -Number.MAX_VALUE;

      for (let i = 0; i < sampleIndices.length; ++i) {
        const sample = this.getSample(sampleIndices[i]).value;

        sum += sample;
        min = Math.min(sample, min);
        max = Math.max(sample, max);
      }

      return {
        min,
        max,
        avg: (sum / sampleIndices.length),
        start: this.getSample(sampleIndices[0]).value,
        end: this.getSample(sampleIndices.length - 1).value
      };
    },

    shiftTimestampsForward(amount) {
      for (let i = 0; i < this.timestamps_.length; ++i) {
        this.timestamps_[i] += amount;
        this.samples_[i].timestamp = this.timestamps_[i];
      }
    },

    * childEvents() {
      yield* this.samples_;
    },

    * childEventContainers() {
    }
  };

  return {
    CounterSeries,
  };
});
</script>
